/*
 * Copyright (c) 2025 Huawei Device, Inc. Ltd. and <马弓手>.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "NetworkManager.h"
#include "CordovaViewController.h"
#include "PluginManager.h"
#include <BasicServicesKit/oh_commonevent_support.h>

REGISTER_PLUGIN_CLASS(NetworkManager)

void NetworkManager::onMessage(const string &id, const string& data)
{
    if(id == "networkconnection" && data != TYPE_NONE) {
        m_checkNetStatus.Stop();
    }
}

bool NetworkManager::execute(const string&  actionAsString, cJSON* args, CallbackContext cbc)
{
    if(actionAsString == "getConnectionInfo") {
        m_cbc = cbc;
        getConnectionInfo();
        return true;
    }
    return false;
}

bool NetworkManager::CreateSubscribeInfo()
{
    const char* events[2];
    events[0] = COMMON_EVENT_CONNECTIVITY_CHANGE;
    events[1] = COMMON_EVENT_NETWORK_STATE_CHANGED;
    
    // 创建订阅者信息
    m_info = OH_CommonEvent_CreateSubscribeInfo(events, 2);
    if(m_info == nullptr) {
        return false;
    }
    
    //设置订阅者权限
    if(OH_CommonEvent_SetPublisherPermission(m_info, "") != COMMONEVENT_ERR_OK) {
        return false;
    }
    
    return true;
}

void NetworkManager::DestroySubscribeInfo()
{
    OH_CommonEvent_DestroySubscribeInfo(m_info);
    m_info = nullptr;
}

bool NetworkManager::CreateSubscriber()
{
    m_subscriber =  OH_CommonEvent_CreateSubscriber(m_info, NetworkManager::onRevice);
    if(m_subscriber == nullptr) {
        return false;
    }
    return true;
}

void NetworkManager::DestroySubscriber()
{
    OH_CommonEvent_DestroySubscriber(m_subscriber);
    m_subscriber = nullptr;
}

bool NetworkManager::Subscribe()
{
    if(OH_CommonEvent_Subscribe(m_subscriber) != COMMONEVENT_ERR_OK) {
        return false;
    }
    return true;
}

bool NetworkManager::UnSubscribe()
{
    if(OH_CommonEvent_UnSubscribe(m_subscriber) != COMMONEVENT_ERR_OK) {
        return false;
    }
    return true;
}

void NetworkManager::pluginInitialize()
{
    if(!CreateSubscribeInfo()) {
        return;
    } else if(!CreateSubscriber()) {
        return;
    } else if(!Subscribe()) {
        return;
    }
}

void NetworkManager::getConnectionInfo()
{
    int hasDefaultNet;
    int tmp = OH_NetConn_HasDefaultNet(&hasDefaultNet);
    if(tmp != 0) {
        sendUpdate(TYPE_NONE);
        return;
    }
    NetConn_NetHandle netHandle;
    if(OH_NetConn_GetDefaultNet(&netHandle) != 0) {
        sendUpdate(TYPE_NONE);
        return;
    }
    NetConn_NetCapabilities netConn_NetCapabilities;
    if(OH_NetConn_GetNetCapabilities(&netHandle, &netConn_NetCapabilities) != 0) {
        sendUpdate(TYPE_NONE);
        return;
    }
    
    if(netConn_NetCapabilities.bearerTypesSize <= 0) {
        sendUpdate(TYPE_NONE);
        return;
    }
    
    if(netConn_NetCapabilities.bearerTypes[0] == NETCONN_BEARER_CELLULAR) {
        sendUpdate(TYPE_4G);
    } else if(netConn_NetCapabilities.bearerTypes[0] == NETCONN_BEARER_WIFI) {
        sendUpdate(TYPE_WIFI);
    } else if(netConn_NetCapabilities.bearerTypes[0] == NETCONN_BEARER_ETHERNET) {
        sendUpdate(TYPE_ETHERNET);
    } else {
        sendUpdate(TYPE_UNKNOWN);
    }
    return;
}

void NetworkManager::onRevice(const CommonEvent_RcvData *data)
{
    NetworkManager* pNetworkManager = (NetworkManager*)((CordovaViewController*)Application::g_cordovaViewController)->getPluginManager()->getPlugin("NetworkStatus");
    pNetworkManager->updateConnectInfo(data);
}

void NetworkManager::updateConnectInfo(const CommonEvent_RcvData *data)
{
    // 获取回调公共事件名称
    string strEvent = OH_CommonEvent_GetEventFromRcvData(data);
    if(strEvent != COMMON_EVENT_CONNECTIVITY_CHANGE && strEvent != COMMON_EVENT_NETWORK_STATE_CHANGED) {
        return;
    }
    
    // 获取回调公共事件结果代码
    int code = OH_CommonEvent_GetCodeFromRcvData(data);
    
    const char* dataStr = OH_CommonEvent_GetDataStrFromRcvData(data);
    
    // 获取回调公共事件附件信息
    const CommonEvent_Parameters *parameters = OH_CommonEvent_GetParametersFromRcvData(data);
    
    int netType = 0;
    if (OH_CommonEvent_HasKeyInParameters(parameters, "NetType")) {
        netType = OH_CommonEvent_GetIntFromParameters(parameters, "NetType", 0);
    }
    
    //开发者官方缺失对参数的类型文档说明，无法确定其意义，在收到事件后，只能直接调用获取网络信息
    getConnectionInfo();
}

void NetworkManager::sendUpdate(string type) 
{
    if(m_cbc.getQueue() != NULL) {
        PluginResult result(PluginResult::Status::OK, type);
        result.setKeepCallback(true);
        m_cbc.sendPluginResult(result);
    } 
    PluginManager* pluginManager = (PluginManager*)getPluginManage();
    pluginManager->postMessage("networkconnection", type.c_str());
    
    if(type == TYPE_NONE) {
        if(!m_checkNetStatus.IsRunning()) {
            m_checkNetStatus.Start(this);
        }
    }
}

void NetworkManager::CheckNetStatus::Execute(void* arg)
{
    while(!GetStopFlag()) {
        checkNetStatus(arg);
        sleep(5);
    }
}

void NetworkManager::CheckNetStatus::checkNetStatus(void* arg)
{
    NetworkManager* pNetwork = (NetworkManager*)arg;
    pNetwork->getConnectionInfo();
}